from .base import BaseAdmAPIView, APIView
from django.contrib import auth
from .exceptions import JsonAPIException
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
from . import ErrCode
import time
from .utils import model2dict, field2info, upload
from django.apps import apps
from qiniu import Auth, put_file, etag
import qiniu.config
from sdks.qiniu.uploade import storage
from django.http import JsonResponse

# Create your views here.

def admin_upload_token(request):
    from django.contrib.auth.models import User as DjangoUser
    import base64
    import json
    import time
    from sdks.aliyunsdkcore import client
    from sdks.aliyunsdkcore.profile import region_provider
    from sdks.aliyunsdksts.request.v20150401 import AssumeRoleRequest
    from tuntun.settings import ALIYUN_OSS
    from django.http import HttpResponse
    user = request.user
    # if not ( isinstance(user, DjangoUser) and user.groups.all().filter(name='SUPERUSER')):
    # x修改
    # if not (isinstance(user, DjangoUser) and (user.is_superuser==True)):
    #     return HttpResponse(json.dumps({'code': 'PARAM_ERROR', 'msg': '无权限', }), status=402)
    # 构建一个 Aliyun Client, 用于发起请求
    # 构建Aliyun Client时需要设置AccessKeyId和AccessKeySevcret

    # image_file = request.FILES.get('logo_public_file_id--file-input')
    # print(image_file)

    REGIONID = 'cn-beijing'
    # ENDPOINT = 'sts.cn-beijing.aliyuncs.com'
    ENDPOINT = 'sts.oss-cn-beijing.aliyuncs.com'
    # 配置要访问的STS Endpoint
    # region_provider.add_endpoint('Sts', REGIONID, ENDPOINT)
    # 初始化Client
    clt = client.AcsClient(ALIYUN_OSS['AccessKeyId'], ALIYUN_OSS['AccessKeySecret'], REGIONID)
    # 构造"AssumeRole"请求
    request = AssumeRoleRequest.AssumeRoleRequest()
    # 指定角色
    request.set_RoleArn(ALIYUN_OSS['WriterRolArn'])
    # 指定策略
    # request.set_Policy("acs:ram::1287791869884451:role/ossman")
    # 设置会话名称，审计服务使用此名称区分调用者
    request.set_RoleSessionName('sdadfaa')
    print(request)
    # 发起请求，并得到response
    try:
        import ssl
        ssl._create_default_https_context = ssl._create_unverified_context
        response = clt.do_action_with_exception(request)
        print(response)
    except Exception as e:
        print(e)
    resp = json.loads(response)
    print(resp)

    del resp['AssumedRoleUser']
    del resp['RequestId']
    resp['bucket'] = ALIYUN_OSS['bucket']
    callback_body = {
        "callbackUrl": ALIYUN_OSS['callback_url'],
        "callbackHost": ALIYUN_OSS['callback_host'],
        "callbackBody": "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}",
        "callbackBodyType": "application/x-www-form-urlencoded",
    }
    base64_callback_body = base64.b64encode(json.dumps(callback_body).encode())
    # resp['callback'] = base64_callback_body.decode()
    resp['callback_body'] = callback_body
    resp['oss_cdn_endpoint'] = ALIYUN_OSS['oss_cdn_endpoint']
    resp['h5_params'] = {
        'accessid': resp['Credentials']['AccessKeyId'],
        'host': ALIYUN_OSS['oss_endpoint'].replace('http:', 'https:'),
        'signature': resp['Credentials']['SecurityToken'],
        'expire': time.time()+1800,
        'callback': str(base64_callback_body),
        'dir': 'ad/vs/',
    }
    return HttpResponse(json.dumps(resp))


# def admin_upload_token(request):
#     from django.contrib.auth.models import User as DjangoUser
#     import base64
#     import json
#     import time
#     from aliyunsdkcore import client
#     from aliyunsdkcore.profile import region_provider
#     # from aliyunsdksts.request.v20150401 import AssumeRoleRequest
#     from aliyunsdkecs.request.v20140526 import DescribeInstancesRequest
#     from aliyunsdkecs.request.v20140526 import StopInstanceRequest
#     from tuntun.settings import ALIYUN_OSS
#     from django.http import HttpResponse
#     user = request.user
#     # if not ( isinstance(user, DjangoUser) and user.groups.all().filter(name='SUPERUSER')):
#     # x修改
#     # if not (isinstance(user, DjangoUser) and (user.is_superuser==True)):
#     #     return HttpResponse(json.dumps({'code': 'PARAM_ERROR', 'msg': '无权限', }), status=402)
#     # 构建一个 Aliyun Client, 用于发起请求
#     # 构建Aliyun Client时需要设置AccessKeyId和AccessKeySevcret
#
#     # image_file = request.FILES.get('logo_public_file_id--file-input')
#     # print(image_file)
#
#     REGIONID = 'cn-beijing'
#     # ENDPOINT = 'sts.cn-beijing.aliyuncs.com'
#     ENDPOINT = 'sts.oss-cn-beijing.aliyuncs.com'
#     # 配置要访问的STS Endpoint
#     region_provider.add_endpoint('Sts', REGIONID, ENDPOINT)
#     # 初始化Client
#     clt = client.AcsClient(ALIYUN_OSS['AccessKeyId'], ALIYUN_OSS['AccessKeySecret'], REGIONID)
#
#     request = DescribeInstancesRequest.DescribeInstancesRequest()
#     request.set_PageSize(10)
#
#     try:
#         response = clt.do_action_with_exception(request)
#         print(response)
#     except Exception as e:
#         print(e)
#     resp = json.loads(response)
#
#     # del resp['AssumedRoleUser']
#     del resp['RequestId']
#     resp['bucket'] = ALIYUN_OSS['bucket']
#     callback_body = {
#         "callbackUrl": ALIYUN_OSS['callback_url'],
#         "callbackHost": ALIYUN_OSS['callback_host'],
#         "callbackBody": "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}",
#         "callbackBodyType": "application/x-www-form-urlencoded",
#     }
#     base64_callback_body = base64.b64encode(json.dumps(callback_body).encode())
#     print(base64_callback_body)
#     # resp['callback'] = base64_callback_body.decode()
#     resp['callback_body'] = callback_body
#     resp['oss_cdn_endpoint'] = ALIYUN_OSS['oss_cdn_endpoint']
#     resp['h5_params'] = {
#         'accessid': "STS."+ALIYUN_OSS['AccessKeyId'],
#         'host': ALIYUN_OSS['oss_endpoint'].replace('http:', 'https:'),
#         # 'signature': resp['Credentials']['SecurityToken'],
#         'expire': time.time()+1800,
#         'callback': str(base64_callback_body),
#         'dir': 'ad/vs/',
#     }
#     print(resp)
#     return HttpResponse(json.dumps(resp))



class LoginView(BaseAdmAPIView):
    permission_classes = ()
    def post(self, request, *args, **kwargs):
        username = request.data.get('username')
        password = request.data.get('password')

        user = auth.authenticate(username=username, password=password)
        if user is None or not user.is_active:
            raise JsonAPIException(code=ErrCode.PARAM_ERROR.name, msg='登录信息错误或已禁用')

        auth.login(request, user)

        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = {
            "uid": user.id,
            'expire_at': time.time()+8640000
        }
        token = jwt_encode_handler(payload)

        user_info = {
            "uid": user.id,
            'username': user.username,
            'access_token': token,
        }

        return Response(user_info)


class ModelsView(BaseAdmAPIView):
    def get(self, request, *args, **kwargs):
        def is_registered_app(a):
            if self.only_apps:
                if a in self.only_apps:
                    return True
                else:
                    return False
            else:
                if a in self.exclude_apps:
                    return False
                else:
                    return True

        res = {}
        all_models = apps.all_models
        res['count'] = len(all_models.keys())
        res['items'] = [
            {
                'app_name': app,
                'app_label': apps.get_app_config(app).verbose_name,
                'models': [
                    {
                        'model_name': model,
                        'model_label': model_class._meta.verbose_name,
                        'fields': [
                            field2info(field)
                            for field in model_class._meta.fields if field.name not in getattr(model_class, 'ignore_fields', [])
                        ] + getattr(model_class, 'get_properties', lambda: [])()
                    }
                    for model, model_class in all_models[app].items()
                ]
            }
            for app in all_models.keys() if is_registered_app(app)
        ]
        return Response(res)


class ListAndCreateView(BaseAdmAPIView):
    def get(self, request, *args, **kwargs):
        model_object = self.get_model(request, *args, **kwargs)

        res = {}
        o = kwargs.get('o', '').strip()

        objs = model_object.objects.filter()
        if o:
            objs = objs.order_by(*o.split('.'))
        count, page_objs = self.page_objects(request, objs)
        res['count'] = count
        res['items'] = [model2dict(po) for po in page_objs]
        return Response(res)


class SingleView(BaseAdmAPIView):
    def get(self, request, *args, **kwargs):
        model_object = self.get_model(request, *args, **kwargs)

        try:
            obj = model_object.objects.get(pk=kwargs.get('id', ''))
        except model_object.DoesNotExist:
            raise JsonAPIException(code=ErrCode.PARAM_ERROR.name, msg='资源不存在', status=404)

        return Response(model2dict(obj))